<?php
 /*
 * 公共调用的函数库
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 232df938b0444d160e57437d90af5bfed3030ded $
 * @time       14-2-7 上午10:27
 */
defined('IN_IXDCW') or exit('Access Denied');


/**
 * location 重定向
 * @param $url
 */
function dheader($url) {
	global $DT;
	if (!defined('DT_ADMIN') && $DT['defend_reload']) sleep($DT['defend_reload']);
	exit(header('location:' . $url));
}

/**
 * 显示右上角提示.
 * @param string $dmsg
 * @param string $dforward
 * @see Prompt::tip
 * @deprecated
 */
function dmsg($dmsg = '', $dforward = '') {
	if (!$dmsg && !$dforward) {
		$dmsg = Cookie::get('dmsg');
		if ($dmsg) {
			// common.js @showmsg
			echo '<script type="text/javascript" defer="defer">showmsg(\'' . $dmsg . '\');</script>';
			Cookie::set('dmsg', '');
		}
	} else {
		Cookie::set('dmsg', $dmsg);
		$dforward = preg_replace("/(.*)([&?]rand=[0-9]*)(.*)/i", "\\1\\3", $dforward);
		$dforward = str_replace('.php&', '.php?', $dforward);
		$dforward = strpos($dforward, '?') === false ? $dforward . '?rand=' . mt_rand(10, 99) : str_replace('?', '?rand=' . mt_rand(10, 99) . '&', $dforward);
		dheader($dforward);
	}
}

/**
 * @param      $var
 * @param int  $precision
 * @param bool $sprinft
 * @return float|string 格式化为标准的round数值
 */
function dround($var, $precision = 2, $sprinft = false) {
	$var = round(floatval($var), $precision);
	if ($sprinft) $var = sprintf('%.' . $precision . 'f', $var);
	return $var;
}

/**
 * allocation 配置
 * @param     $i
 * @param int $n
 * @return float
 */
function dalloc($i, $n = 5000) {
	return ceil($i / $n);
}

/**
 * sql 过滤
 * @param $string
 * @return array|mixed
 */
function strip_sql($string) {
	$search  = array("/union[\s|\t]/i", "/select[\s|\t]/i", "/update[\s|\t]/i", "/outfile[\s|\t]/i", "/ascii/i", "/[\s|\t]or[\s|\t]/i", "/\/\*/i");
	$replace = array('union&nbsp;', 'select&nbsp;', 'update&nbsp;', 'outfile&nbsp;', 'ascii&nbsp;', '&nbsp;or&nbsp;', '');
	return is_array($string) ? array_map('strip_sql', $string) : preg_replace($search, $replace, $string);
}

/**
 * 返回缓存模版页面如不存在则生成文件
 * 由于不能传入公共变量, 所以这里必须返回字串进行处理
 * @param String $template 文件名称
 * @param String $dir      文件额外路径
 * @return string 文件路径
 */
function template($template = 'index', $dir = '') {
	global $CFG;
	if (isset($CFG['refactorTpl'])) {
		$to = $dir ? DT_CACHE . '/' . $CFG['refactorTpl'] . '/' . $dir . '.' . $template . '.php' : DT_CACHE . '/' . $CFG['refactorTpl'] . '/' . $template . '.php';
	} else {
		$to = $dir ? DT_CACHE . '/tpl/' . $dir . '.' . $template . '.php' : DT_CACHE . '/tpl/' . $template . '.php';
	}

	$isfileto = is_file($to);
	if ($CFG['template_refresh'] || !$isfileto) {
		if ($dir) $dir = $dir . '/';
		if (isset($CFG['refactorTpl'])) {
			$from = DT_ROOT . '/' . $CFG['refactorTpl'] . '/' . $dir . $template . '.htm';
		} else {
			$from = DT_ROOT . '/template/' . $CFG['template'] . '/' . $dir . $template . '.htm';
		}

		if (!is_file($from)) {
			exit("模版文件'{$from}'不存在!");
		}
		/*目标文件不存在 或 模版文件被更改 或 缓存文件与模版文件大小不一致  */
		if (!$isfileto || filemtime($from) > filemtime($to) || (filesize($to) == 0 && filesize($from) > 0)) {
			require_once DT_INC . '/template.func.php';
			template_compile($from, $to);
		}
	}
	return $to;
}

/**
 * 将模版数据缓存到字串中去
 * @param        $template
 * @param string $dir
 * @return string
 */
function ob_template($template, $dir = '') {
	extract($GLOBALS, EXTR_SKIP);
	ob_start();
	include template($template, $dir);
	$contents = ob_get_contents();
	ob_clean();
	return $contents;
}


/**
 * 检测是否登录,否则跳转到会员的登陆界面
 */
function login() {
	global $_userid, $MODULE, $DT_URL, $DT;
	$_userid or Header::location($MODULE[2]['linkurl'] . $DT['file_login'] . '?forward=' . rawurlencode($DT_URL));
}

/**
 * 检测个人资料是否完善,否则跳转到个人资料编辑页面
 */
function isCompleteData() {
	global $_username,$db,$AREA;
	$userdata=userinfo($_username);
	$parents = explode(',',$AREA[$userdata['areaid']]['arrparentid']);
	if(empty($userdata['truename']) || !$userdata['areaid']){

		Cookie::set('jumpUrl', Env::uri());
		Prompt::message('请先完善个人资料',url('member/edit', 'tab=1'));

	}elseif( !$userdata['cityid'] || !in_array($userdata['cityid'],$parents)){

		if($db->count($db->getPre().'city','areaid='.$userdata['areaid'])){
			$cityid = $userdata['areaid'];
		}else{
			if(count($parents) <=1 )Prompt::message('请先完善个人资料，选择所在地区',url('member/edit', 'tab=1'));
			foreach($parents as $v){
				if($db->count($db->getPre().'city','areaid='.$v)){
					$cityid = $v;
				}
			}
		}
		$db->query(Sql::update($db->getPre().'member',"cityid=$cityid","userid=".$userdata['userid']));
	}
}

/**
 * 获取表的名称, 如果是 article/info, 则是可复制的,使用_$moduleid类型.
 * @param     $moduleid 模块ID
 * @param int $data     是否是数据表
 * @return string       表名称
 * @deprecated
 */
function get_table($moduleid, $data = 0) {
	global $db, $MODULE;
	$module = $MODULE[$moduleid]['module'];
	if ($moduleid == 26) $module = 'information';
	if ($data) {
		return in_array($module, array('article', 'info')) ? $db->getPre() . $module . '_data_' . $moduleid : $db->getPre() . $module . '_data';
	} else {
		return in_array($module, array('article', 'info')) ? $db->getPre() . $module . '_' . $moduleid : $db->getPre() . $module;
	}
}

/**
 * 获取进程状态
 * @param $fromtime
 * @param $totime
 * @return int
 */
function get_process($fromtime, $totime) {
	global $DT_TIME;
	if ($fromtime && $DT_TIME < $fromtime) return 1;
	if ($totime && $DT_TIME > $totime) return 3;
	return 2;
}

/**
 * 给某人发送消息
 * @param        $touser
 * @param        $title
 * @param        $content
 * @param int    $typeid
 * @param string $fromuser
 * @return bool
 */
function send_message($touser, $title, $content, $typeid = 4, $fromuser = '') {
	global $db, $DT_TIME, $DT_IP;
	if ($touser == $fromuser) return false;
	if (User::checkname($touser) && $title && $content) {
		$title   = addslashes($title);
		$content = addslashes($content);
		$r       = $db->getOne("SELECT black FROM {$db->getPre()}member WHERE username='$touser'");
		if ($r) {
			if ($r['black'] && $typeid != 4) {
				$blacks = explode(' ', $r['black']);
				$_from  = $fromuser ? $fromuser : 'Guest';
				if (in_array($_from, $blacks)) return false;
			}
			$db->query("INSERT INTO {$db->getPre()}message (title,typeid,touser,fromuser,content,addtime,ip,status) VALUES ('$title', $typeid, '$touser','$fromuser','$content','$DT_TIME','$DT_IP',3)");
			$db->query("UPDATE {$db->getPre()}member SET message=message+1 WHERE username='$touser'");
			if ($fromuser) {
				$db->query("INSERT INTO {$db->getPre()}message (title,typeid,content,fromuser,touser,addtime,ip,status) VALUES ('$title','$typeid','$content','$fromuser','$touser','$DT_TIME','$DT_IP','2')");
			}
			return true;
		}
	}
	return false;
}

/**
 * 发送邮件
 * @param        $mail_to
 * @param        $mail_subject
 * @param        $mail_body
 * @param string $mail_from
 * @param bool   $mail_sign
 * @return int
 */
function send_mail($mail_to, $mail_subject, $mail_body, $mail_from = '', $mail_sign = true) {
	global $DT;
	require_once DT_INC . '/mail.func.php';
	$result  = dmail(trim($mail_to), $mail_subject, $mail_body, $mail_from, $mail_sign);
	$success = $result == 'SUCCESS' ? 1 : 0;
	if ($DT['mail_log']) {
		global $DT_TIME, $db;
		$status       = $success ? 3 : 2;
		$note         = $success ? '' : addslashes($result);
		$mail_subject = stripslashes($mail_subject);
		$mail_body    = stripslashes($mail_body);
		$mail_subject = addslashes($mail_subject);
		$mail_body    = addslashes($mail_body);
		$db->query("INSERT INTO {$db->getPre()}mail_log (email,title,content,addtime,status,note) VALUES ('$mail_to','$mail_subject','$mail_body','$DT_TIME','$status','$note')");
	}
	return $success;
}

/**
 * 信息过滤
 * @param $message
 * @return mixed|string
 */
function strip_sms($message) {
	global $DT;
	$message = strip_tags($message);
	$message = preg_replace("/&([a-z]{1,});/", '', $message);
	$message = str_replace(' ', '', $message);
	if ($DT['sms_sign']) $message .= $DT['sms_sign'];
	return $message;
}

/**
 * 发送sms
 * @param     $mobile
 * @param     $message
 * @param int $word
 * @param int $time
 * @return bool|string
 */
function send_sms($mobile, $message, $word = 0, $time = 0) {
	global $db, $DT, $DT_TIME, $DT_IP, $_username;
	if (!$DT['sms'] || !$DT['sms_uid'] || !$DT['sms_key']) return false;
	$word or $word = Str::length($message);
	$sms_message = rawurlencode(Str::convert($message, DT_CHARSET, 'UTF-8'));
	$data        = 'sms_uid=' . $DT['sms_uid'] . '&sms_key=' . $DT['sms_key'] . '&sms_charset=' . DT_CHARSET . '&sms_mobile=' . $mobile . '&sms_message=' . $sms_message . '&sms_time=' . $time;
	$header      = "POST /send.php HTTP/1.0\r\n";
	$header .= "Accept: */*\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Content-Length: " . strlen($data) . "\r\n\r\n";
	$DT['sms_host'] or $DT['sms_host'] = 'sms';
	$fp   = fsockopen($DT['sms_host'] . '.destoon.com', 8820);
	$code = '';
	if ($fp) {
		fputs($fp, $header . $data);
		while (!feof($fp)) {
			$code .= fgets($fp, 1024);
		}
		fclose($fp);
		if ($code && strpos($code, 'destoon_sms_code=') !== false) {
			$code = explode('destoon_sms_code=', $code);
			$code = $code[1];
		} else {
			$code = 'Can Not Connect SMS Server';
		}
	} else {
		$code = 'Can Not Connect SMS Server';
	}
	$db->query("INSERT INTO {$db->getPre()}sms (mobile,message,word,editor,sendtime,code) VALUES ('$mobile','$message','$word','$_username','$DT_TIME','$code')");
	return $code;
}


/**
 * 获取内容表格的表名称
 * @param        $moduleid 模块id
 * @param        $itemid   条目id
 * @param        $split    是否分表
 * @param string $table_data
 * @return string
 */
function content_table($moduleid, $itemid, $split, $table_data = '') {
	if ($split) {
		return split_table($moduleid, $itemid);
	} else {
		$table_data or $table_data = get_table($moduleid, 1);
		return $table_data;
	}
}

/**
 * 内容分表
 * @param $moduleid
 * @param $itemid
 * @return string
 */
function split_table($moduleid, $itemid) {
	global $db;
	$part = split_id($itemid);



	return $db->getPre() . $moduleid . '_' . $part;
}

/**
 * 根据ID进行分表
 * @param $id
 * @return float|int
 */
function split_id($id) {
	return $id > 0 ? ceil($id / 500000) : 1;
}


/**
 * @param $IP ip禁止
 */
function banip($IP) {
	global $DT_IP, $DT_TIME;
	$ban = false;
	foreach ($IP as $v) {
		if ($v['totime'] && $v['totime'] < $DT_TIME) continue;
		if ($v['ip'] == $DT_IP) {
			$ban = true;
			break;
		}
		if (preg_match("/^" . str_replace('*', '[0-9]{1,3}', $v['ip']) . "$/", $DT_IP)) {
			$ban = true;
			break;
		}
	}
	if ($ban) Prompt::message(lang('include->msg_ip_ban', array($DT_IP)));
}

/**
 * @param      $WORD
 * @param      $string
 * @param bool $extend
 * @return string       将禁止词替换
 */
function banword($WORD, $string, $extend = true) {
	$string = stripslashes($string);
	foreach ($WORD as $v) {
		$v[0] = preg_quote($v[0]);
		$v[0] = str_replace('/', '\/', $v[0]);
		$v[0] = str_replace("\*", ".*", $v[0]);
		if ($v[2] && $extend) {
			if (preg_match("/" . $v[0] . "/i", $string)) Prompt::alert(lang('include->msg_word_ban'));
		} else {
			if ($string == '') break;
			if (preg_match("/" . $v[0] . "/i", $string)) $string = preg_replace("/" . $v[0] . "/i", $v[1], $string);
		}
	}
	return addslashes($string);
}


/**
 * 获取类型
 * @param     $item
 * @param int $cache
 * @return array|mixed|string
 */
function get_type($item, $cache = 0) {
	$types = array();
	if ($cache) {
		$types = PCache::read('type-' . $item . '.php');
	} else {
		global $db;
		$result = $db->query("SELECT * FROM {$db->getPre()}type WHERE item='$item' ORDER BY listorder ASC,typeid DESC ");
		while ($r = $db->fetchArray($result)) {
			$types[$r['typeid']] = $r;
		}
	}
	return $types;
}

/**
 * 获取分类父分类
 * @param int $catid 需要获取分类id
 * @return array
 * @author sameal
 */
function get_parentidarray($catid) {
	global $db;
	$catid         = intval($catid);
	$r             = $db->getOne("SELECT * FROM {$db->getPre()}category WHERE catid=$catid");
	$parentidarray = explode(",", $r['arrparentid']);
	return $parentidarray;
}

/**
 * 获取分类信息
 * @param  int $catid 需要获取分类的id
 * @return array      获取的catid
 */
function get_cat($catid) {
	global $db;
	$catid = intval($catid);
	return $catid ? $db->getOne("SELECT * FROM {$db->getPre()}category WHERE catid=$catid") : array();
}

/**
 * 获取pos的位置
 * @param array  $CAT    传递给的本类别的变量
 * @param string $str    分隔符
 * @param string $target 打开窗口的方式.
 * @return string        返回的a链接的字串
 */
function cat_pos($CAT, $str = ' &raquo; ', $target = '') {
	global $MODULE, $db;
	if (!$CAT) return '';
	$arrparentids = $CAT['arrparentid'] . ',' . $CAT['catid'];
	$arrparentid  = explode(',', $arrparentids);
	$pos          = '';
	$target       = $target ? ' target="_blank"' : '';
	$CATEGORY     = array();
	$sql          = "SELECT catid,moduleid,catname,linkurl FROM {$db->getPre()}category WHERE catid IN ($arrparentids)";
	$result       = $db->query($sql);
	while ($r = $db->fetchArray($result)) {
		$CATEGORY[$r['catid']] = $r;
	}
	foreach ($arrparentid as $catid) {
		if (!$catid || !isset($CATEGORY[$catid])) continue;
		$pos .= '<a href="' .url($MODULE[$CATEGORY[$catid]['moduleid']]['module'].'/list','catid='.$catid) . '"' . $target . '>' . $CATEGORY[$catid]['catname'] . '</a>' . $str;
	}
	$_len = strlen($str);
	if ($str && substr($pos, -$_len, $_len) === $str) $pos = substr($pos, 0, strlen($pos) - $_len);
	return $pos;
}


/**
 * 招商类型获取
 * @param array  $CAT    传递给的本类别的变量
 * @param string $str    分隔符
 * @param string $target 打开窗口的方式.
 * @return string        返回的a链接的字串
 */
function cat_posType($CAT, $str = ' &raquo; ', $target = '') {
	global $MODULE, $db;
	if (!$CAT) return '';
	$arrparentids = $CAT['arrparentid'] . ',' . $CAT['catid'];
	$arrparentid  = explode(',', $arrparentids);
	$pos          = '';
	$target       = $target ? ' target="_blank"' : '';
	$CATEGORY     = array();
	$sql          = "SELECT catid,moduleid,catname,linkurl FROM {$db->getPre()}category WHERE catid IN ($arrparentids)";
	$result       = $db->query($sql);
	while ($r = $db->fetchArray($result)) {
		$CATEGORY[$r['catid']] = $r;
	}
	foreach ($arrparentid as $catid) {
		if (!$catid || !isset($CATEGORY[$catid])) continue;
		$pos .= '<a href="' . $MODULE[$CATEGORY[$catid]['moduleid']]['linkurl'] . $CATEGORY[$catid]['linkurl'] . '"' . $target . '>' . $CATEGORY[$catid]['catname'] . '</a>';
		return $pos;
	}

}


/**
 * 获取pos的位置
 * @param array  $CAT    传递给的本类别的变量
 * @param string $str    分隔符
 * @param string $target 打开窗口的方式.
 * @return string        返回的a链接的字串
 */
function catPos($CAT, $str = ' &raquo; ', $target = '') {
	global $MODULE, $db, $MOD;
	if (!$CAT) return '';
	$arrparentids = $CAT['arrparentid'] . ',' . $CAT['catid'];
	$arrparentid  = explode(',', $arrparentids);
	$pos          = '';
	$target       = $target ? ' target="_blank"' : '';
	$CATEGORY     = array();
	$sql          = "SELECT catid,moduleid,catname,linkurl FROM {$db->getPre()}category WHERE catid IN ($arrparentids)";
	$result       = $db->query($sql);
	while ($r = $db->fetchArray($result)) {
		$CATEGORY[$r['catid']] = $r;
	}
	foreach ($arrparentid as $catid) {
		if (!$catid || !isset($CATEGORY[$catid])) continue;
		$pos .= '<a href="' . $MOD['linkurl'] . '?catid=' . $CATEGORY[$catid]['catid'] . '"' . $target . '>' . $CATEGORY[$catid]['catname'] . '</a>' . $str;
	}
	$_len = strlen($str);
	if ($str && substr($pos, -$_len, $_len) === $str) $pos = substr($pos, 0, strlen($pos) - $_len);
	return $pos;
}

/**
 * 返回分类链接地址
 * @var int $catid 分类id
 * @return string
 */
function cat_url($catid) {
	global $MODULE, $db;
	$r = $db->getOne("SELECT moduleid,linkurl FROM {$db->getPre()}category WHERE catid=$catid");
	return $r ? $MODULE[$r['moduleid']]['linkurl'] . $r['linkurl'] : '';
}

/**
 * 返回地区讯息
 * @var int $areaid 地区id
 * @return multitype:
 */
function get_area($areaid) {
	global $db;
	$areaid = intval($areaid);
	return $db->getOne("SELECT * FROM {$db->getPre()}area WHERE areaid=$areaid");
}

/**
 * 生成完整的区域的名称
 * @param int    $areaid 区域ID
 * @param string $str    分隔符
 * @param int    $deep
 * @return Ambigous <string>|string
 */
function area_pos($areaid, $str = ' &raquo; ', $deep = 0, $without = 0) {
	if ($areaid) {
		global $AREA;
	} else {
		global $L;
		return $L['allcity'];
	}
	$AREA or $AREA = PCache::read('area.php');
	$arrparentid   = $AREA[$areaid]['arrparentid'] ? explode(',', $AREA[$areaid]['arrparentid']) : array();
	$arrparentid[] = $areaid;
	$pos           = '';
	if ($deep || $without) $i = 1;
	foreach ($arrparentid as $areaid) {
		if (!$areaid || !isset($AREA[$areaid])) continue;
		if ($without) {
			if ($areaid == $without) {
				$i++;
				continue;
			}
		}
		if ($deep) {
			if ($i > $deep) continue;
		}
		if ($deep || $without) {
			$i++;
		}
		$pos .= $AREA[$areaid]['areaname'] . $str;
	}
	$_len = strlen($str);
	if ($str && substr($pos, -$_len, $_len) === $str) $pos = substr($pos, 0, strlen($pos) - $_len);
	return $pos;
}


function coshop($moduleid, $child, $level) {
	global $db;
	$contion = "moduleid=$moduleid AND child=$child AND level=$level";
	$cat     = array();
	$result  = $db->query("SELECT catid,catname,child,style,level,linkurl,item,thumb FROM {$db->getPre()}category WHERE $contion ORDER BY listorder,catid ASC", 'CACHE');
	while ($r = $db->fetchArray($result)) {
		$cat[$r['catid']] = $r;
	}
	return $cat;
}

/**
 * 获取父id
 * @param $catid
 * @param $moduleid
 * @param $level
 * @return array|void
 */
function get_parentid($catid, $moduleid, $level = -1) {
	global $db;
	$condition = $catid ? "catid=$catid" : "moduleid=$moduleid AND parentid=0";
	if ($level >= 0) $condition .= " AND level=$level";
	$r = $db->getOne("SELECT catid,catname,child,style,linkurl,item,parentid FROM {$db->getPre()}category WHERE $condition", 'CACHE');
	return $r;
}

/**
 * 获取子ids
 * @param $areaid
 * @return array
 */
function get_mainarea($areaid) {
	global $db;
	$areaid = intval($areaid);
	$are    = array();
	$result = $db->query("SELECT areaid,areaname FROM {$db->getPre()}area WHERE parentid=$areaid ORDER BY listorder,areaid ASC", 'CACHE');
	while ($r = $db->fetchArray($result)) {
		$are[] = $r;
	}
	return $are;
}

/**
 * 获取用户信息
 * @param        $value
 * @param string $key
 * @param string $from
 * @return mixed
 */
function get_user($value, $key = 'username', $from = 'userid') {
	global $db;
	$r = $db->getOne("SELECT `$from` FROM {$db->getPre()}member WHERE `$key`='$value'");
	return $r[$from];
}

/**
 * 车型库获取汽车车型信息
 * @param        $value
 * @param string $key
 * @param string $from
 * @return mixed
 */
function get_carName($value, $key = 'arid', $from = 'name') {
	global $db;
	$r = $db->getOne("SELECT `$from` FROM {$db->getPre()}auto_category WHERE `$key`='$value'");
	return $r[$from];
}

function get_carNameUrl($value, $key = 'arid', $from = 'name') {
	global $db;
	$r = $db->getOne("SELECT * FROM {$db->getPre()}auto_category WHERE `$key`='$value'");
	return $r;
}

/**
 * 车型库获取汽车车款信息
 * @param        $value
 * @param string $key
 * @param string $from
 * @return mixed
 */
function get_carModuleid($value, $key = 'amid', $from = 'name') {
	global $db;
	$r = $db->getOne("SELECT `$from` FROM {$db->getPre()}auto_model WHERE `$key`='$value'");
	return $r[$from];
}

/**
 * 检测群组权限
 * @param $groupid
 * @param $groupids
 * @return bool
 */
function check_group($groupid, $groupids) {
	// 没有权限检测和 管理员群组
	if (!$groupids || $groupid == 1) return true;
	// 待审核会员组等同于游客组
	if ($groupid == 4) $groupid = 3;
	// 检测权限是否存在
	return in_array($groupid, explode(',', $groupids));
}

/**
 * 生成静态页面
 * @param        $htmlfile  静态文件的名称, index首页
 * @param string $module    模块名称文件夹
 * @param string $parameter 额外的参数
 */
function tohtml($htmlfile, $module = '', $parameter = '') {
	defined('TOHTML') or define('TOHTML', true);
	extract($GLOBALS, EXTR_SKIP);
	if ($parameter) parse_str($parameter);
	// 如果是模块则更新模块,否则更新 include/xx.htm.php
	include $module ? DT_CORE . '/' . $module . '/' . $htmlfile . '.htm.php' : DT_INC . '/' . $htmlfile . '.htm.php';
}

/**
 * 设置标题颜色
 * @param        $string
 * @param string $style
 * @param string $tag
 * @return string
 */
function set_style($string, $style = '', $tag = 'span') {
	if (preg_match("/^#[0-9a-zA-Z]{6}$/", $style)) $style = 'color:' . $style;
	return $style ? '<' . $tag . ' style="' . $style . '">' . $string . '</' . $tag . '>' : $string;
}

/**
 * captcha 检测
 * @param      $captcha
 * @param int  $enable
 * @param bool $return
 * @param      $url
 * @return mixed|string|void
 */
function captcha($captcha, $enable = 1, $return = false, $url = '') {
	global $DT_IP, $DT;
	if ($enable) {
		if ($DT['captcha_cn']) {
			if (strlen($captcha) < 4) {
				$msg = lang('include->captcha_missed');
				return $return ? $msg : Prompt::message($msg, $url);
			}
		} else {
			if (!preg_match("/^[0-9a-z]{4,}$/i", $captcha)) {
				$msg = lang('include->captcha_missed');
				return $return ? $msg : Prompt::message($msg, $url);
			}
		}
		Session::start();
		if (!isset($_SESSION['captchastr'])) {
			$msg = lang('include->captcha_expired');
			return $return ? $msg : Prompt::message($msg, $url);
		}
		if ($_SESSION['captchastr'] != md5(md5(strtoupper($captcha) . DT_KEY . $DT_IP))) {
			$msg = lang('include->captcha_error');
			return $return ? $msg : Prompt::message($msg, $url);
		}
		unset($_SESSION['captchastr']);
	} else {
		return '';
	}
}

/**
 * 问题匹配
 * @param      $answer
 * @param int  $enable
 * @param bool $return
 * @return mixed|string|void
 */
function question($answer, $enable = 1, $return = false) {
	global $DT_IP;
	if ($enable) {
		if (!$answer) {
			$msg = lang('include->answer_missed');
			return $return ? $msg : Prompt::message($msg);
		}
		$answer = stripslashes($answer);
		Session::start();
		if (!isset($_SESSION['answerstr'])) {
			$msg = lang('include->question_expired');
			return $return ? $msg : Prompt::message($msg);
		}
		if ($_SESSION['answerstr'] != md5(md5($answer . DT_KEY . $DT_IP))) {
			$msg = lang('include->answer_error');
			return $return ? $msg : Prompt::message($msg);
		}
		unset($_SESSION['answerstr']);
	} else {
		return '';
	}
}

/**
 * 分页函数
 * @param        $total   总页数
 * @param int    $page    当前页
 * @param int    $perpage 每页的数量
 * @param string $demo
 * @param int    $step
 * @return string
 */
function pages($total, $page = 1, $perpage = 20, $demo = '', $step = 2) {
	global $DT_URL, $DT, $L;
	if ($total <= $perpage) return '';
	$items = $total;
	$total = ceil($total / $perpage);
	if ($page < 1 || $page > $total) $page = 1;
	if ($demo) {
		$demo_url = $demo;
		$home_url = str_replace('{destoon_page}', '1', $demo_url);
	} else {
		if (defined('DT_REWRITE') && $DT['rewrite'] && $_SERVER["SCRIPT_NAME"]) {
			$demo_url = $_SERVER["SCRIPT_NAME"];
			$demo_url = str_replace('//', '/', $demo_url); //Fix Nginx
			$mark     = false;
			if (substr($demo_url, -4) == '.php') {
				if (strpos($_SERVER['QUERY_STRING'], '.html') === false) {
					$qstr = '';
					if ($_SERVER['QUERY_STRING']) {
						if (substr($_SERVER['QUERY_STRING'], -5) == '.html') {
							$qstr = '-' . substr($_SERVER['QUERY_STRING'], 0, -5);
						} else {
							parse_str($_SERVER['QUERY_STRING'], $qs);
							foreach ($qs as $k => $v) {
								$qstr .= '-' . $k . '-' . rawurlencode($v);
							}
						}
					}
					$demo_url = substr($demo_url, 0, -4) . '-htm-page-{destoon_page}' . $qstr . '.html';
				} else {
					$demo_url = substr($demo_url, 0, -4) . '-htm-' . $_SERVER['QUERY_STRING'];
					$mark     = true;
				}
			} else {
				$mark = true;
			}
			if ($mark) {
				if (strpos($demo_url, '%') === false) $demo_url = rawurlencode($demo_url);
				$demo_url = str_replace(array('%2F', '%3A'), array('/', ':'), $demo_url);
				if (strpos($demo_url, '-page-') !== false) {
					$demo_url = preg_replace("/page-([0-9]+)/", 'page-{destoon_page}', $demo_url);
				} else {
					$demo_url = str_replace('.html', '-page-{destoon_page}.html', $demo_url);
				}
			}
			$home_url = str_replace('-page-{destoon_page}', '-page-1', $demo_url);
		} else {
			$DT_URL   = str_replace('&amp;', '&', $DT_URL);
			$demo_url = $home_url = preg_replace("/(.*)([&?]page=[0-9]*)(.*)/i", "\\1\\3", $DT_URL);
			$s        = strpos($demo_url, '?') === false ? '?' : '&';
			$demo_url = $demo_url . $s . 'page={destoon_page}';
		}
	}
	$pages = '';
	include DT_ROOT . '/api/pages.' . ($DT['pages_mode'] ? 'sample' : 'default') . '.php';
	return $pages;
}

/**
 * @param     $CAT
 * @param     $total
 * @param int $page
 * @param int $perpage
 * @param int $step
 * @return string
 */
function listpages($CAT, $total, $page = 1, $perpage = 20, $step = 2) {
	global $DT, $MOD, $L;
	if ($total <= $perpage) return '';
	$items = $total;
	$total = ceil($total / $perpage);
	if ($page < 1 || $page > $total) $page = 1;
	$home_url = $MOD['linkurl'] . $CAT['linkurl'];
	$pages    = '';
	include DT_ROOT . '/api/pages.' . ($DT['pages_mode'] ? 'sample' : 'default') . '.php';
	return $pages;
}

/**
 * 显示分页
 * @param     $item
 * @param     $total
 * @param int $page
 * @return string
 */
function showpages($item, $total, $page = 1) {
	global $MOD, $L;
	$pages    = '';
	$home_url = $MOD['linkurl'] . itemurl($item);
	$demo_url = $MOD['linkurl'] . itemurl($item, '{destoon_page}');
	$_page    = $page <= 1 ? $total : ($page - 1);
	$url      = $_page == 1 ? $home_url : str_replace('{destoon_page}', $_page, $demo_url);
	$pages .= '<input type="hidden" id="destoon_previous" value="' . $url . '"/><a href="' . $url . '" title="' . $L['prev_page'] . '">&nbsp;&#171;&nbsp;</a> ';
	for ($_page = 1; $_page <= $total; $_page++) {
		$url = $_page == 1 ? $home_url : str_replace('{destoon_page}', $_page, $demo_url);
		$pages .= $page == $_page ? '<strong>&nbsp;' . $_page . '&nbsp;</strong> ' : ' <a href="' . $url . '">&nbsp;' . $_page . '&nbsp;</a>  ';
	}
	$_page = $page >= $total ? 1 : $page + 1;
	$url   = $_page == 1 ? $home_url : str_replace('{destoon_page}', $_page, $demo_url);
	$pages .= '<a href="' . $url . '" title="' . $L['next_page'] . '">&nbsp;&#187;&nbsp;</a> <input type="hidden" id="destoon_next" value="' . $url . '"/>';
	return $pages;
}

/**
 * 修正链接地址
 * @param     $linkurl 链接地址
 * @param int $absurl  是否是绝对地址
 * @return string
 */
function linkurl($linkurl, $absurl = 1) {
	global $CFG;
	if ($absurl) {
		if (strpos($linkurl, '://') !== false) return $linkurl;
		return strpos($linkurl, $CFG['path']) === 0 ? $CFG['url'] . substr($linkurl, strlen($CFG['path'])) : $CFG['url'] . $linkurl;
	} else {
		if (strpos($linkurl, '://') !== false) return strpos($linkurl, $CFG['url']) === 0 ? $CFG['path'] . substr($linkurl, strlen($CFG['url'])) : $linkurl;
		return strpos($linkurl, $CFG['path']) === 0 ? $linkurl : $CFG['path'] . $linkurl;
	}
}

/**
 * 图片地址交换符号
 * @param string $imgurl
 * @param int    $absurl
 * @return string
 */
function imgurl($imgurl = '', $absurl = 1) {
	return $imgurl ? $imgurl : CSSIMG_URL.'common/nopic.gif';
}

/**
 * 返回用户的访问地址
 * @param        $username 用户名
 * @param string $qstring  查询的字串
 * @param string $domain   域名
 * @return string           返回用户的访问地址
 */
function userurl($username, $qstring = '', $domain = '') {
	global $CFG, $DT, $MODULE;
	$URL       = '';
	$subdomain = 0;
	if ($CFG['com_domain']) $subdomain = substr($CFG['com_domain'], 0, 1) == '.' ? 1 : 2;
	if ($username) {
		if ($subdomain || $domain) {
			$URL = $domain ? 'http://' . $domain . '/' : ($subdomain == 1 ? 'http://' . ($DT['com_www'] ? 'www.' : '') . $username . $CFG['com_domain'] . '/' : 'http://' . $CFG['com_domain'] . '/' . $username . '/');
			if ($qstring) {
				parse_str($qstring, $q);
				if (isset($q['file'])) {
					$URL .= $CFG['com_dir'] ? $q['file'] . '/' : 'company/' . $q['file'] . '/';
					unset($q['file']);
				}
				if ($q) {
					if ($DT['rewrite']) {
						foreach ($q as $k => $v) {
							$v = rawurlencode($v);
							$URL .= $k . '-' . $v . '-';
						}
						$URL = substr($URL, 0, -1) . '.shtml';
					} else {
						$URL .= 'index.php?';
						$i = 0;
						foreach ($q as $k => $v) {
							$v = rawurlencode($v);
							$URL .= ($i++ == 0 ? '' : '&') . $k . '=' . $v;
						}
					}
				}
			}
		} else if ($DT['rewrite']) {
			$URL = SITE_URL . 'com/' . $username . '/';
			if ($qstring) {
				parse_str($qstring, $q);
				if (isset($q['file'])) {
					$URL .= $CFG['com_dir'] ? $q['file'] . '/' : 'company/' . $q['file'] . '/';
					unset($q['file']);
				}
				if ($q) {
					foreach ($q as $k => $v) {
						$v = rawurlencode($v);
						$URL .= $k . '-' . $v . '-';
					}
					$URL = substr($URL, 0, -1) . '.html';
				}
			}
		}
	} else {
		$URL = linkurl($MODULE[4]['linkurl'], 1) . 'guest.php';
	}
	return $URL;
}

/**
 * 用户信息
 * @param        $useritem
 * @param string $cache
 * @param string $fields
 * @param string $type
 * @return mixed
 */
function userinfo($useritem, $cache = '', $fields = '*', $type = 'username') {
	global $db;
	if ($type == 'username') {
		$where = "m.username='$useritem'";
	} elseif ($type == 'userid') {
		$where = "m.userid=$useritem";
	}
	$sql = "SELECT $fields FROM {$db->getPre()}member m, {$db->getPre()}company c WHERE m.userid=c.userid AND {$where}";
	return $db->getOne($sql, $cache);
}

function memberinfo($useritem, $cache = '', $fields = '*', $type = 'username') {
	global $db;
	if ($type == 'username') {
		$where = "username='$useritem'";
	} elseif ($type == 'userid') {
		$where = "userid=$useritem";
	}
	return $db->getOne("SELECT $fields FROM {$db->getPre()}member WHERE {$where}", $cache);
}

/**
 * 条目页URL
 * @param     $item
 * @param int $page
 * @return mixed|string
 */
function itemurl($item, $page = 0) {
	global $DT, $MOD, $L;
	if ($MOD['show_html'] && $item['filepath']) {
		if ($page === 0) return $item['filepath'];
		$ext = File::ext($item['filepath']);
		return str_replace('.' . $ext, '_' . $page . '.' . $ext, $item['filepath']);
	}
	include DT_ROOT . '/api/url.inc.php';
	$group = PCache::read("grouporder.php"); //读取缓存会员组排序
	if (!$group) {
		Xd_save_groupcachefile();
	}
	$moduledir = $MOD['moduledir'];
	$file_ext  = $DT['file_ext'];
	$index     = $DT['index'];
	$itemid    = $item['itemid'];
	$username  = $item['username'];
	$groupid   = get_user($item['username'], 'username', 'groupid');
	$title     = File::vname($item['title']);
	$addtime   = $item['addtime'];
	$catid     = $item['catid'];
	$year      = date('Y', $addtime);
	$month     = date('m', $addtime);
	$day       = date('d', $addtime);
	$prefix    = $MOD['htm_item_prefix'];
	$urlid     = $MOD['show_html'] ? $MOD['htm_item_urlid'] : $MOD['php_item_urlid'];
	$ext       = $MOD['show_html'] ? 'htm' : 'php';
	$alloc     = dalloc($itemid);
	//如果会员是企业会员 并且此模块数据内容页为企业黄页内数据
	if ($urlid == 4 && !$MOD['show_html']) {
		if (in_array($groupid, explode(',', $group['qiye']))) {
			$url = $urls[$ext]['item'][$urlid];
		} else {
			$url = $urls[$ext]['item'][0];
		}
	} else {
		$url = $urls[$ext]['item'][$urlid];
	}
	$url = $page ? $url['page'] : $url['index'];
	if (strpos($url, 'cat') !== false && $catid) {
		$cate    = get_cat($catid);
		$catdir  = $cate['catdir'];
		$catname = $cate['catname'];
	}
	eval("\$itemurl = \"$url\";");
	if (substr($itemurl, 0, 1) == '/') $itemurl = substr($itemurl, 1);
	if ($urlid == 4 && in_array($groupid, explode(',', $group['qiye']))) {
		$itemurl = SITE_URL . $itemurl;
	}
	return $itemurl;
}

/**
 * 重写URL
 * @param     $url
 * @param int $encode
 * @return string
 */
function rewrite($url, $encode = 0) {
	global $DT, $CFG;
	if (!$DT['rewrite']) return $url;
	if (strpos($url, '.php?') === false || strpos($url, '=') === false) return $url;
	$url = str_replace(array('+', '-'), array('%20', '%20'), $url);
	$url = str_replace(array('.php?', '&', '='), array('-htm-', '-', '-'), $url) . '.html';
	return $url;
}

/**
 * 将给定的unix时间戳转换为日期格式
 * @param int $time 给定的时间戳
 * @param int $type 类型, 详情见函数设置
 *                  0   'Y-m-d'
 *                  1   'Y'
 *                  2   'm-d'
 *                  3   'Y-m-d'
 *                  4   'm-d H:i'
 *                  5   'Y-m-d H:i'
 *                  6   'Y-m-d H:i:s'
 *                  7   'YmdHi'
 *                  8   'Ymd'
 * @return string       时间格式
 */
function timetodate($time = 0, $type = 6) {
	if (!$time) {
		global $DT_TIME;
		$time = $DT_TIME;
	}
	$types = array('Y-m-d', 'Y', 'm-d', 'Y-m-d', 'm-d H:i', 'Y-m-d H:i', 'Y-m-d H:i:s', 'YmdHi', 'Ymd');
	if (isset($types[$type])) $type = $types[$type];
	return date($type, $time);
}

/**
 * 日志记录
 * @param        $message
 * @param string $type
 */
function log_write($message, $type = 'php') {
	global $DT_IP, $DT_TIME, $_username;
	if (!DT_DEBUG) return;
	$DT_IP or $DT_IP = Env::ip();
	$DT_TIME or $DT_TIME = time();
	$user = $_username ? $_username : 'guest';
	$log  = "<$type>\n";
	$log .= "\t<time>" . date('Y-m-d H:i:s', $DT_TIME) . "</time>\n";
	$log .= "\t<ip>" . $DT_IP . "</ip>\n";
	$log .= "\t<user>" . $user . "</user>\n";
	$log .= "\t<file>" . $_SERVER['SCRIPT_NAME'] . "</file>\n";
	$log .= "\t<querystring>" . str_replace('&', '&amp;', $_SERVER['QUERY_STRING']) . "</querystring>\n";
	$log .= "\t<message>" . $message . "\t</message>\n";
	$log .= "</$type>";
	File::put(DT_ROOT . '/file/log/' . date('Ym', $DT_TIME) . '/' . $type . '-' . date('Y.m.d H.i.s', $DT_TIME) . '-' . strtolower(Str::random(10)) . '.xml', $log);
}

/**
 * 如果类型 是 less, css, js, htm, 则输出内容
 * 如果是 lang,则加载 lang 文件夹下的 扩展inc.php配置文件
 * @param $file String 加载的文件名称
 * @return String 返回需要加载的字串
 */
function load($file) {
    //获取文件的扩展名
	$ext = File::ext($file);
	if ($ext == 'css') {
		echo '<link rel="stylesheet" href="' . DT_SKIN . $file . '?version=' . XD_VERSION_BUILD . '">' . PHP_EOL;
	} else if ($ext == 'js') {
		echo '<script src="' . SITE_URL . 'file/script/' . $file . '?version=' . XD_VERSION_BUILD . '"></script>' . PHP_EOL;
	} else if ($ext == 'htm') {
		$file = str_replace('ad_m', 'ad_t6_m', $file);
		if (is_file(DT_CACHE . '/htm/' . $file)) {
			$content = File::get(DT_CACHE . '/htm/' . $file);
			if (substr($content, 0, 4) == '<!--') $content = substr($content, 17);
			echo $content;
		} else {
			echo '';
		}
	} else if ($ext == 'lang') {
		$file = str_replace('.lang', '.inc.php', $file);
		return DT_ROOT . '/lang/' . DT_LANG . '/' . $file;
    }
}

/**
 * 广告加载
 * @param        $id
 * @param int    $cid
 * @param string $kw
 * @param int    $tid
 * @return String
 */
function ad($id, $cid = 0, $kw = '', $tid = 0) {
	global $cityid;
	if (!is_int($id)) {
		$id = get_adid($id);
	}
	if ($tid) {
		if ($kw) {
			$file = 'ad_t' . $tid . '_m' . $id . '_k' . urlencode($kw);
		} else if ($cid) {
			$file = 'ad_t' . $tid . '_m' . $id . '_c' . $cid;
		} else {
			$file = 'ad_t' . $tid . '_m' . $id;
		}
		$a3 = 'ad_' . $id . '_d' . $tid . '.htm';
	} else {
		$file = 'ad_' . $id;
		$a3   = 'ad_' . $id . '_d0.htm';
	}
	$a1 = $file . '_' . $cityid . '.htm';
	if (is_file(DT_CACHE . '/htm/' . $a1)) return load($a1);
	$a2 = $file . '_0.htm';
	if (is_file(DT_CACHE . '/htm/' . $a2)) return load($a2);
	if (is_file(DT_CACHE . '/htm/' . $a3)) return load($a3);
}

/**
 * 读取文件内容
 * @author Sameal
 */
function load_content($file) {
	$file = str_replace('ad_m', 'ad_t6_m', $file);
	if (is_file(DT_CACHE . '/htm/' . $file)) {
		$content = File::get(DT_CACHE . '/htm/' . $file);
		if (substr($content, 0, 4) == '<!--') $content = substr($content, 17);
		return $content;
	} else {
		return '';
	}
}

/**
 * 返回广告位id
 * @author Sameal
 * @param String $name 广告位名称
 * @return $id            广告位id
 */
function get_adid($name) {
	global $db;
	$ad = $db->getOne("SELECT * FROM {$db->getPre()}ad_place WHERE name like '$name %'");
	return $ad['pid'];
}

/**
 * 判断分别读取总站城市站广告信息 注：分站（城市站）广告不寻在返回省级广告 省级不存在返回国级
 * @author Sameal
 * @param String Or int $id1 城市站广告名称或id
 * @param String Or int $id2 分站广告名称或id
 * @return 广告<a> and <img>
 */
function city_ad($id1, $id2) {
	global $cityid;
	if (!is_int($id1) && $id1) {
		$id1 = get_adid($id1);
	}
	if (!is_int($id2) && $id2) {
		$id2 = get_adid($id2);
	}
	if ($cityid && $id2) {
		$file   = 'ad_' . $id2 . '_' . $cityid . '.htm';
		$siteid = get_area($cityid);
		while (!is_file(DT_CACHE . '/htm/' . $file) && $siteid['parentid']) {
			$file   = 'ad_' . $id2 . '_' . $siteid['parentid'] . '.htm';
			$siteid = get_area($siteid['parentid']);
		}
		if (is_file(DT_CACHE . '/htm/' . $file)) return load_content($file);
		$file = 'ad_' . $id2 . '_0.htm';
		if (is_file(DT_CACHE . '/htm/' . $file)) return load_content($file);
	} else if (!$cityid && $id1) {
		$file = 'ad_' . $id1 . '_0.htm';
		if (is_file(DT_CACHE . '/htm/' . $file)) return load_content($file);
	}
	return '';
}

/**
 * 加载广告模版
 * @author Sameal
 * @param string $tem  广告模版名称
 * @param array  $info 广告信息
 *                     return 广告模版
 */
function tem_ad($tem, $info) {
	$has_info = false;
	foreach ($info as $i => $t) {
		$info[$i]['result'] = city_ad($t['city1'], $t['city2']);
		if ($info[$i]['result']) $has_info = true;
	}
	if ($has_info) {
		include template($tem, "ads");
	}
	return $has_info;
}

/**
 * include->msg_word_ban
 * 返回lang目录下 , include.inc.php 文件中的 $L['msg_word_ban']
 * 语言包中的定义的字符.如果是有变量,使用数组的键值做一个替换.
 * @param       $str 显示字串的键值
 * @param array $arr 替换的变量数组
 * @return mixed        返回的字串
 */
function lang($str, $arr = array()) {
	if (strpos($str, '->') !== false) {
		$t = explode('->', $str);
		include load($t[0] . '.lang');
		$str = $L[$t[1]];
	}
	if ($arr) {
		foreach ($arr as $k => $v) {
			$str = str_replace('{V' . $k . '}', $v, $str);
		}
	}
	return $str;
}

/**
 * 自动加载类的函数
 * 系统函数, 并非逻辑函数
 * 系统中不可以"显"示调用
 * 自定义的函数同名的先加载
 * spl_autoload_register('_loadClass');
 * @param $class
 */
function _loadClass($class) {
	$files = array(
		DT_INC . '/logical/' . $class . '.class.php',
		DT_INC . '/module/' . $class . '.class.php',
		DT_INC . '/system/' . $class . '.class.php',
		DT_INC . '/' . $class . '.class.php',
	);

	$thirdClassFiles = array(
		'Smarty'          => 'smarty/Smarty.php',
		'PhpThumbFactory' => 'phpthumb/ThumbLib.inc.php',
		'PHPExcel'        => 'PHPExcel/PHPExcel.inc.php',
	);
	if (!class_exists($class)) {
		// for SomeDb
		if (substr($class, -2) == 'Db') {
			$classFile = DT_INC.'/Db/'.substr($class, 0, strrpos($class, 'Db')).'.php';
			if (file_exists($classFile)) {
				require_once $classFile;
			}
		}

		// for XXOOAction
		if (substr($class, -6) == 'Action') {
			$classFile = DT_INC.'/Action/'.substr($class, 0, strrpos($class, 'Action')).'.php';
			if (file_exists($classFile)) {
				require_once $classFile;
			}
		}
		// for Mustache_Engine
		if (strpos($class, '_') !== false) {
			$classFile = DT_INC . '/' . str_replace('_', '/', $class) . '.php';
			if (file_exists($classFile)) {
				require_once $classFile;
			}
		}
		if (array_key_exists($class, $thirdClassFiles)) {
			$classFile = DT_INC . '/' . $thirdClassFiles[$class];
			require_once $classFile;
		} else {
			foreach ($files as $file) {
				if (file_exists($file)) {
					require_once $file;
				}
			}
		}
	}
}

function _userErrorHandler($errno, $errstr, $errfile, $errline) {
	if (!(error_reporting() & $errno)) {
		// This error code is not included in error_reporting
		return;
	}

	switch ($errno) {

		case E_USER_ERROR:
			echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
			echo "  Fatal error on line $errline in file $errfile";
			echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
			echo "Aborting...<br />\n";
			exit(1);
			break;
		case E_USER_WARNING:
			echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
			break;
		case E_USER_DEPRECATED:
			echo "<b>My DEPRECATED</b> [$errno] $errstr<br />\n";
			break;
		case E_USER_NOTICE:
			echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
			break;
		default:
			echo "Unknown error type: [$errno] $errstr<br />\n";
			break;
	}

	/* Don't execute PHP internal error handler */
	return true;
}

function userError($errorInfo, $errorLevel) {
	if (DT_DEBUG || XD_DEBUG) {
		trigger_error($errorInfo, $errorLevel);
	}
}

/**
 * debug错误
 */
function debug() {
	global $db, $debug_starttime;
	$mtime = explode(' ', microtime());
	$s     = number_format(($mtime[1] + $mtime[0] - $debug_starttime), 3);
	echo 'Processed in ' . $s . ' second(s), ' . $db->querynum . ' queries';
	if (function_exists('memory_get_usage')) echo ', Memory ' . round(memory_get_usage() / 1024 / 1024, 2) . ' M';
}

/**
 * 获取扩展的设置
 * @param string $key
 * @return array|mixed|string
 */
function extend_setting($key = '') {
	global $EXT;
	return $key ? $EXT[$key] : $EXT;
}


/**
 * 招商
 * 获取 $catid $moduleid 下所有子分类讯息
 * @var int $catid    分类id
 * @var int $moduleid 模块id
 * @var int $level    推荐等级
 * @return array:array:  $catid $moduleid下所有子分类讯息
 */
function get_maincat($catid, $moduleid, $level = -1) {
	//if($catid==3152){$catid=1;}
	global $db;
	$condition = $catid ? "parentid=$catid" : "moduleid=$moduleid AND parentid=0";
	if ($level >= 0) $condition .= " AND level=$level";
	$cat    = array();
	$result = $db->query("SELECT catid,catname,child,style,linkurl,item,thumb FROM {$db->getPre()}category WHERE $condition ORDER BY listorder,catid ASC", 'CACHE');
	while ($r = $db->fetchArray($result)) {
		$cat[$r['catid']] = $r;
	}
	return $cat;
}

/**
 * @返回 类别菜单
 * @author Sameal
 * @param $CAT
 * @param $moduleid
 * @return catid list
 */
function Xd_get_catlist($CAT, $moduleid, $level = -1) {
	$layer      = 0;
	$catid_next = $CAT;
	if ($catid_next['child'] != 1) {
		$catid_next = get_cat($catid_next['parentid']);
	}
	while ($catid_next['catid'] != 0) {
		$maincat[$layer] = get_maincat($catid_next['catid'], $moduleid);
		$layer           = $layer + 1;
		$catid_next      = get_cat($catid_next['parentid']);
	}
	$maincat[$layer] = get_maincat($catid_next['catid'], $moduleid, $level);
	//倒序排列
	$array_key    = array_keys($maincat);
	$array_value  = array_values($maincat);
	$array_return = array();

	for ($i = 1, $size_of_array = sizeof($array_key); $i <= $size_of_array; $i++) {
		$array_return[$array_key[$size_of_array - $i]] = $array_value[$size_of_array - $i];
	}
	$maincat = $array_return;
	return $maincat;
}

function Xd_get_arealist($ARE) {
	//制作菜单列表
	$layer       = 0;
	$areaid_next = $ARE;
	if ($areaid_next['child'] != 1) {
		$areaid_next = get_area($areaid_next['parentid']);
	}

	while ($areaid_next['areaid'] != 0) {
		$mainarea[$layer] = get_mainarea($areaid_next['areaid']);
		$layer            = $layer + 1;
		$areaid_next      = get_area($areaid_next['parentid']);
	}
	$mainarea[$layer] = get_mainarea($areaid_next['areaid']);
	//倒序排列
	$array_key    = array_keys($mainarea);
	$array_value  = array_values($mainarea);
	$array_return = array();

	for ($i = 1, $size_of_array = sizeof($array_key); $i <= $size_of_array; $i++) {
		$array_return[$array_key[$size_of_array - $i]] = $array_value[$size_of_array - $i];
	}

	$mainarea = $array_return;
	return $mainarea;
}

/*
 * 新版制作菜单列表
 *
 */
function Xd_get_arealists($ARE) {
	//制作菜单列表
	$layer       = 0;
	$areaid_next = $ARE;
	if ($areaid_next['child'] != 1) {
		$areaid_next = get_area($areaid_next['parentid']);
	}
	$mainarea[$layer] = get_mainarea($areaid_next['areaid']);
	//$mainarea[$layer] = get_mainarea($areaid_next['areaid']);
	//倒序排列
	$array_key    = array_keys($mainarea);
	$array_value  = array_values($mainarea);
	$array_return = array();

	for ($i = 1, $size_of_array = sizeof($array_key); $i <= $size_of_array; $i++) {
		$array_return[$array_key[$size_of_array - $i]] = $array_value[$size_of_array - $i];
	}

	$mainarea = $array_return;
	return $mainarea;
}

/**
 * @author   sameal
 * @tutorial 存储按会员级别排序序列到 缓存文件
 */
function Xd_save_groupcachefile() {
	$group = array();
	global $db;
	$result = $db->query("SELECT groupid,memtype,memlevel FROM xd_member_group ORDER BY memlevel ASC");
	while ($r = $db->fetchArray($result)) {
		$group['DESC'] .= $r['groupid'] . ',';
		$group['ASC'] .= $r['groupid'] . ',';
		if ($r['memtype'] >= 5) {
			$group['qiye'] = $group['qiye'] . $r['groupid'] . ',';
		}
		if ($r['memtype'] == 6) {
			$group['type6'] = $group['type6'] . $r['groupid'] . ',';
		}
		if ($r['memtype'] == 7) {
			$group['type7'] = $group['type7'] . $r['groupid'] . ',';
		}
		if ($r['memtype'] == 8) {
			$group['type8'] = $group['type8'] . $r['groupid'] . ',';
		}
		if ($r['memlevel'] == 1) {
			$group['level1'] = $group['level1'] . $r['groupid'] . ',';
		}
		if ($r['memlevel'] == 2) {
			$group['level2'] = $group['level2'] . $r['groupid'] . ',';
		}
		if ($r['memlevel'] == 3) {
			$group['level3'] = $group['level3'] . $r['groupid'] . ',';
		}
	}
	$group['DESC']   = "locate(groupid,'" . trim($group['DESC'], ',') . "') DESC";
	$group['ASC']    = "locate(groupid,'" . trim($group['ASC'], ',') . "') ASC";
	$group['type6']  = trim($group['type6'], ',');
	$group['type7']  = trim($group['type7'], ',');
	$group['type8']  = trim($group['type8'], ',');
	$group['qiye']   = trim($group['qiye'], ',');
	$group['level1'] = trim($group['level1'], ',');
	$group['level2'] = trim($group['level2'], ',');
	$group['level3'] = trim($group['level3'], ',');
	PCache::write("grouporder.php", "<?php defined('IN_IXDCW') or exit('Access Denied'); return " . '$group=array("DESC"=>"' . $group[DESC] . '","ASC"=>"' . $group[ASC] . '","type6"=>"' . $group['type6'] . '","type7"=>"' . $group['type7'] . '","type8"=>"' . $group['type8'] . '","qiye"=>"' . $group['qiye'] . '","level1"=>"' . $group['level1'] . '","level2"=>"' . $group['level2'] . '","level3"=>"' . $group['level3'] . '"' . ')' . "?>");
}


function XD_GetPostsByFid($fid, $start = 0, $limit = 5, $order = 'dateline', $sort = 'DESC', $recommends = 0, $displayorder = 1) {
	$url = BBS_URL . "api.php?mod=cx&fid=$fid&start=$start&limit=$limit&order=$order&sort=$sort&recommends=$recommends&displayorder=$displayorder";
	if ($fid) {
		$content = file_get_contents($url);
		if ($content) {
			$arr = array();
			foreach (json_decode($content) as $k => $v) {
				$arr[$k] = $v;
			}
			return $arr;
		} else {
			return NULL;
		}
	} else {
		return NULL;
	}
}

function xd_debug($info, $dump = true) {
	if (XD_DEBUG) {
		if ($dump) {
			var_dump($info);
		} else {
			echo str_pad('-', 20) . "\n";
			print_r($info);
			echo str_pad('-', 20) . "\n";
		}
	}
}


function timer_start() {
	global $timer;
	$timer = microtime(true);
}

function timer_end() {
	global $timer;
	return microtime(true) - $timer;
}

/**
 * __ underscore 方法
 * Returns an instance of __ for OO-style calls
 * @param null $item
 * @return __
 */
function __($item = null) {
	$__ = new __();
	if (func_num_args() > 0) $__->_wrapped = $item;
	return $__;
}

/**
 * 车主服务
 * 获取 $catid $moduleid 下所有子分类讯息
 * @var int $catid    分类id
 * @var int $moduleid 模块id
 * @var int $level    推荐等级
 * @return array:array:  $catid $moduleid下所有子分类讯息
 */
function get_maincats($catid, $moduleid, $level = 2) {
	//if($catid==3152){$catid=1;}
	global $db;
	$condition = $catid ? "parentid=$catid AND level=$level" : "moduleid=$moduleid AND parentid=3741";
	$cat       = array();
	$result    = $db->query("SELECT catid,catname,child,style,linkurl,item,thumb FROM {$db->getPre()}category WHERE $condition ORDER BY listorder,catid ASC", 'CACHE');
	while ($r = $db->fetchArray($result)) {
		$cat[$r['catid']] = $r;
	}
	return $cat;
}

/**
 * 字符串命名风格转换
 * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
 * @param string $name 字符串
 * @param integer $type 转换类型
 * @return string
 */
function parse_name($name, $type=0) {
	if ($type) {
		return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
	} else {
		return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
	}
}

function Db($tableName){
	static $_classes = array();
	if (!isset($_classes[$tableName])) {
		$className = parse_name($tableName, 1).'Db';
		$classFile = DT_INC.'/Db/'.parse_name($tableName,1).'.php';
		if (file_exists($classFile)) {
			$_classes[$tableName] = new $className();
		} else {
			die('Unexists Db Class '.$className);
		}
	}
	return $_classes[$tableName];
}


/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @return mixed
 */
function C($name=null, $value=null) {
	static $_config = array();
	// 无参数时获取所有
	if (empty($name)) {
		if(!empty($value) && $array = S('c_'.$value)) {
			$_config = array_merge($_config, array_change_key_case($array));
		}
		return $_config;
	}
	// 优先执行设置获取或赋值
	if (is_string($name)) {
		if (!strpos($name, '.')) {
			$name = strtolower($name);
			if (is_null($value))
				return isset($_config[$name]) ? $_config[$name] : null;
			$_config[$name] = $value;
			return;
		}
		// 二维数组设置和获取支持
		$name = explode('.', $name);
		$name[0]   =  strtolower($name[0]);
		if (is_null($value))
			return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
		$_config[$name[0]][$name[1]] = $value;
		return;
	}
	// 批量设置
	if (is_array($name)){
		$_config = array_merge($_config, array_change_key_case($name));
		return;
	}
	return null; // 避免非法参数
}



/**
 * 获取和设置语言定义(不区分大小写)
 * @param string|array $name 语言变量
 * @param string $value 语言值
 * @return mixed
 */
function L($name=null, $value=null) {
	static $_lang = array();
	// 空参数返回所有定义
	if (empty($name))
		return $_lang;
	// 判断语言获取(或设置)
	// 若不存在,直接返回全大写$name
	if (is_string($name)) {
		$name = strtoupper($name);
		if (is_null($value))
			return isset($_lang[$name]) ? $_lang[$name] : $name;
		$_lang[$name] = $value; // 语言定义
		return;
	}
	// 批量定义
	if (is_array($name))
		$_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER));
	return;
}